# coding:utf-8
from typing import Optional

from fastapi import APIRouter, Query, Path, Request, Security
from tortoise.expressions import Q

from app.admin.schemas.system import RoleBase, RoleUpdate, RoleMenuUpdate
from app.core.response import SuccessExtra, Success, Fail
from app.admin.service.system.role import SystemRoleService
from app.dependencies.verify import verify_token

router = APIRouter()


@router.get("/role/list", summary="系统角色列表")
async def page_list(
        page: int = Query(1, description="页码"),
        limit: int = Query(10, description="每页数量"),
        name: str = Query(None, description="用户名称，用于搜索"),
        status: Optional[str] = Query(None, description="用户状态"),
):
    # 查询条件
    query = Q()
    if name:
        query &= Q(name__contains=name)
    if status and int(status) in [0, 1, 2]:
        query &= Q(status__lt=status)
    model_service = SystemRoleService()
    total, lists = await model_service.page_list(query, page, limit)
    data = [await obj.to_dict(m2m=True) for obj in lists]
    return SuccessExtra(data=data, total=total, page=page, limit=limit)


@router.get("/role/{item_id}", summary="查看角色")
async def get_detail(item_id: int = Path(..., description="角色ID"), ):
    model_service = SystemRoleService()
    item_obj = await model_service.get_id(item_id)
    if not item_obj:
        return Fail(msg="角色不存在")
    item_dict = await item_obj.to_dict()
    return Success(data=item_dict)


@router.post("/role/create", summary="创建角色")
async def create(data_in: RoleBase):
    model_service = SystemRoleService()
    # 查询条件
    query = Q()
    query &= Q(name=data_in.name)
    item = await model_service.find(query)
    if item:
        return Fail(msg="角色名称已存在")
    new_item = await model_service.create(obj_in=data_in)
    if not new_item:
        return Fail(msg="用户角色失败")
    return Success(msg="操作成功")


@router.post("/role/update", summary="更新角色")
async def update(data_in: RoleUpdate):
    model_service = SystemRoleService()
    result = await model_service.update(obj_in=data_in)
    return Success(msg="操作成功")


@router.delete("/role/delete/{item_id}", summary="删除角色")
async def delete(item_id: int = Path(..., description="角色ID")):
    model_service = SystemRoleService()
    await model_service.remove(item_id)
    return Success(msg="操作成功")


@router.get("/role/perms/{role_id}", summary="查看角色权限")
async def get_role_auth(role_id: int = Path(..., description="角色ID")):
    model_service = SystemRoleService()
    lists = await model_service.get_role_menu(role_id=role_id)
    return Success(data={"role_id": role_id, "menu_ids": lists})


@router.post("/role/perms", summary="更新角色权限")
async def update_role_auth(data_in: RoleMenuUpdate):
    model_service = SystemRoleService()
    role_obj = await model_service.get_id(data_in.role_id)
    if not role_obj:
        return Fail(msg="角色不存在")
    data = await model_service.update_role_menu(data_in.role_id, data_in.menu_ids)
    return Success(data=data)


@router.post("/role/menus", summary="查看角色菜单", dependencies=[Security(verify_token)])
async def get_role_auth(request: Request):
    role_ids = request.state.role_ids
    if len(role_ids) == 0:
        return Success(data={})
    model_service = SystemRoleService()
    lists = await model_service.get_menu_by_role_id(role_ids=role_ids)
    return Success(data={"role_ids": role_ids, "menu_ids": lists})
